package com.example.jasonrpc.registry.redis;

import com.example.jasonrpc.proto.Peer;
import com.example.jasonrpc.registry.RegistryCenter;
import com.example.jasonrpc.registry.RegistryDirectory;
import com.google.common.base.Splitter;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RedisRegistry implements RegistryCenter {
    private Jedis jedis;

    public RedisRegistry(String centerIp, int centerPort) {
        //连接redis服务端
        jedis = new Jedis(centerIp, centerPort);
    }

    @Override
    public void register(RegistryDirectory registryDirectory) {
    }

    @Override
    public void unregister(RegistryDirectory registryDirectory) {

    }

    @Override
    public List<RegistryDirectory> subscribe(String serviceClass) {
        //目前只能订阅指定服务的主机
        Map<String, String> map = jedis.hgetAll(serviceClass);
        List<Peer> peers = new ArrayList<>();
        for (String peer : map.keySet()) {
            peers.add(new Peer(parseAddr(peer).get(0), Integer.parseInt(parseAddr(peer).get(1))));
        }
        List<RegistryDirectory> directories = new ArrayList<>();
        RegistryDirectory directory = new RegistryDirectory();
        directory.setServiceClass(serviceClass);
        directory.setPeers(peers);
        directories.add(directory);
        return directories;
    }

    private List<String> parseAddr(String str) {
        return Splitter.on(':').splitToList(str.substring(7));
    }
}
